package org.gl.ui.activity;

import net.tsz.afinal.http.AjaxParams;

import org.gl.GlobalVariable;
import org.gl.android.activity.ImageUploadActivity;
import org.gl.ui.manger.AjaxCallBackProxy;
import org.gl.utils.BMapUtil;
import org.gl.utils.Tip;
import org.gl.utils.lg;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.MyLocationOverlay.LocationMode;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.chanceit.ssss.activity.BaseFragmentActivity;
import com.chanceit.ssss.activity.R;
import com.chanceit.ssss.common.IntentExtraDataKey;
import com.chanceit.ssss.common.IntentExtraDataKeyValue;
import com.chanceit.ssss.data.DataSources;
import com.chanceit.ssss.fragments.BaseFragment.webkey;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 此demo用来展示如何结合定位SDK实现定位，并使用MyLocationOverlay绘制定位位置 同时展示如何使用自定义图标绘制并点击时弹出泡泡 <br>
 * http://lbsyun.baidu.com/apiconsole/key?from=developer
 */
public class LocationOverlayActivity extends BaseFragmentActivity {
	private enum E_BUTTON_TYPE {
		LOC, COMPASS, FOLLOW
	}

	private E_BUTTON_TYPE mCurBtnType;

	// 定位相关
	LocationClient mLocClient;
	LocationData locData = null;
	public MyLocationListenner myListener = new MyLocationListenner();

	// 定位图层
	locationOverlay myLocationOverlay = null;
	// 弹出泡泡图层
	private PopupOverlay pop = null;// 弹出泡泡图层，浏览节点时使用
	private TextView popupText = null;// 泡泡view
	private View viewCache = null;

	// 地图相关，使用继承MapView的MyLocationMapView目的是重写touch事件实现泡泡处理
	// 如果不处理touch事件，则无需继承，直接使用MapView即可
	MyLocationMapView mMapView = null; // 地图View
	private MapController mMapController = null;

	// UI相关
	OnCheckedChangeListener radioButtonListener = null;
	Button requestLocButton = null;
	boolean isRequest = false;// 是否手动触发请求定位
	boolean isFirstLoc = true;// 是否首次定位

	DataSources ds;

	private EditText editText1;
	/**
	 * 上传的图片URL
	 */
	private String imageUrl;

	private JSONObject json_hitInfo;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_locationoverlay);
		CharSequence titleLable = "定位功能";
		setTitle(titleLable);
		requestLocButton = (Button) findViewById(R.id.button1);
		mCurBtnType = E_BUTTON_TYPE.LOC;
		OnClickListener btnClickListener = new OnClickListener() {
			public void onClick(View v) {
				switch (mCurBtnType) {
				case LOC:
					// 手动定位请求
					requestLocClick();
					break;
				case COMPASS:
					myLocationOverlay.setLocationMode(LocationMode.NORMAL);
					requestLocButton.setText("定位");
					mCurBtnType = E_BUTTON_TYPE.LOC;
					break;
				case FOLLOW:
					myLocationOverlay.setLocationMode(LocationMode.COMPASS);
					requestLocButton.setText("罗盘");
					mCurBtnType = E_BUTTON_TYPE.COMPASS;
					break;
				}
			}
		};
		requestLocButton.setOnClickListener(btnClickListener);

		RadioGroup group = (RadioGroup) this.findViewById(R.id.radioGroup);
		radioButtonListener = new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if (checkedId == R.id.defaulticon) {
					// 传入null则，恢复默认图标
					modifyLocationOverlayIcon(null);
				}
				if (checkedId == R.id.customicon) {
					// 修改为自定义marker
					// modifyLocationOverlayIcon(getResources().getDrawable(R.drawable.icon_geo));
				}
			}
		};
		group.setOnCheckedChangeListener(radioButtonListener);

		// 地图初始化
		mMapView = (MyLocationMapView) findViewById(R.id.bmapView);
		mMapController = mMapView.getController();
		mMapView.getController().setZoom(16);
		mMapView.getController().enableClick(true);
		mMapView.setBuiltInZoomControls(false);
		// 创建 弹出泡泡图层
		createPaopao();

		// 定位初始化
		mLocClient = new LocationClient(this);
		locData = new LocationData();
		// 监听我的位置变化
		// mLocClient.registerLocationListener(myListener);
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(1000);
		mLocClient.setLocOption(option);
		mLocClient.start();

		// 定位图层初始化
		myLocationOverlay = new locationOverlay(mMapView);
		// 设置定位数据
		myLocationOverlay.setData(locData);
		// 添加定位图层
		mMapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass();
		// 修改定位数据后刷新图层生效
		mMapView.refresh();

		ds = new DataSources();
		int gomapfor = getIntent().getIntExtra(
				IntentExtraDataKey.KEY_GOMAP_FOR,
				IntentExtraDataKey.KEY_UNVALUE_UNKNOW);
		switch (gomapfor) {
		case IntentExtraDataKey.KEY_GOMAP_FORHIT:
			if (IntentExtraDataKeyValue.getUserInfoToIntent() != null) {
				json_hitInfo = IntentExtraDataKeyValue.getUserInfoToIntent();
				loadGPSinfo(ds, json_hitInfo.toString());
				initHitHandlerView(json_hitInfo);
				modifyLocationOverlayIcon(getResources().getDrawable(R.drawable.ic_marker_offline));
			} else {
				Tip.show("碰撞信息为空");
			}
			break;

		default:
			getCareGpsInfo(IntentExtraDataKeyValue.getUserInfoToIntent());
			break;
		}
	}

	/**
	 * 初始化碰撞处理的视图
	 * 
	 * @param userInfoToIntent
	 */
	private void initHitHandlerView(JSONObject userInfoToIntent) {
		findViewById(R.id.map_rl_handhit).setVisibility(View.VISIBLE);
		findViewById(R.id.ll_sendmessage).setVisibility(View.VISIBLE);
		findViewById(R.id.sendMessage).setOnClickListener(this);
		findViewById(R.id.pickImage).setVisibility(View.GONE);
		findViewById(R.id.pickImage).setOnClickListener(this);
		editText1 = (EditText) findViewById(R.id.editText1);
		TextView tv_hitTime = (TextView) findViewById(R.id.map_rl_handhit_time);
		tv_hitTime.setText("碰撞时间:"+userInfoToIntent.optString("hitTime") + "");
		TextView tv_hitPlace = (TextView) findViewById(R.id.map_rl_handhit_place);
		tv_hitPlace.setText("碰撞车辆:"+userInfoToIntent.optString("userName")+"(" +userInfoToIntent.optString("seriesName") + ")");
	}

	/**
	 * 得到用户的GPS位置
	 * 
	 * @param userInfoToIntent
	 */
	private void getCareGpsInfo(JSONObject userInfoToIntent) {

		ds.getCarerGpsInfo(userInfoToIntent.optString("identifier"),
				new AjaxCallBackProxy<String>(findViewById(R.id.loading)) {

					@Override
					public void onStart() {
						super.onStart();
					}

					@Override
					public void onSuccess(String t) {
						super.onSuccess(t);
						loadGPSinfo(ds, t);
					}

					@Override
					public void onFailure(Throwable t, int errorNo,
							String strMsg) {
						switch (errorNo) {
						case 1:
							Tip.show(R.string.err_no_info_location);
							super.onFailure(null, 0, getString(R.string.err_no_info_location));
							break;

						default:
							Tip.show(R.string.err_format);
							super.onFailure(null, 0, getString(R.string.err_no_info_location));
							break;
						}
					}

				});

	}

	private void loadGPSinfo(DataSources ds, String t) {
		lg.i(TAG, "getGPS:" + t);
		if (!TextUtils.isEmpty(t)) {
			// {"uid":"152690301","coordinate":"2631469,9884232"}
			try {
				JSONObject ja = new JSONObject(t);

				String[] locString = ja.optString("coordinate").split(",");
				if (locString == null
						|| (locString[0].equals("0") && locString[1]
								.equals("0"))) {
					Tip.show("coordinate is null");
					return;
				}
				if (locString.length != 2) {
					Tip.show("coordinate parsh fail");
					return;
				}

				ds.converGPS((Double.parseDouble(locString[0]) / (3600 * 24)),
						(Double.parseDouble(locString[1])) / (3600 * 24),
						new AjaxCallBackProxy<String>(
								findViewById(R.id.loading)) {
							@TargetApi(Build.VERSION_CODES.FROYO)
							@Override
							public void onSuccess(String t) {
								lg.i(TAG, "converGPS:" + t);
								if (!TextUtils.isEmpty(t)) {
									// {"uid":"152690301","coordinate":"2631469,9884232"}
									JSONObject ja2;
									try {
										ja2 = new JSONObject(t);
										if (!"0".equals(ja2.optString("error"))) {
											onFailure(null, 0,
													"解析GPS偏移坐标失败");
											return;
										}
										LocationData locData = new LocationData();
										// 通过BASE64 默认解码标准
										// 解码百度返回的坐标值
										lg.i(TAG,
												"base64 to string "
														+ new String(
																Base64.decode(
																		ja2.optString("x"),
																		Base64.DEFAULT))
														+ ""
														+ new String(
																Base64.decode(
																		ja2.optString("y"),
																		Base64.DEFAULT)));
										locData.latitude = Double.parseDouble(new String(
												Base64.decode(
														ja2.optString("y"),
														Base64.DEFAULT)));
										locData.longitude = Double.parseDouble(new String(
												Base64.decode(
														ja2.optString("x"),
														Base64.DEFAULT)));
										// http://www.chanceit.cn:82/baidu/convert/y:30.1525/x:114.2323
										// //FIXME 坐标转换 Y为经度
										// X是维度
										moveToLocation(locData);
										this.loadSuccessed();
									} catch (JSONException e) {
										e.printStackTrace();
										onFailure(null, 0, e.getMessage());
									} catch (NumberFormatException e) {
										onFailure(null, 0, e.getMessage());
									}
								}
							};
						});

			} catch (Exception e) {
				Tip.show("数据异常");
				e.printStackTrace();
			}
		}
	}

	/**
	 * 手动触发一次定位请求
	 */
	public void requestLocClick() {
		isRequest = true;
		mLocClient.requestLocation();
		Toast.makeText(LocationOverlayActivity.this, "正在定位……",
				Toast.LENGTH_SHORT).show();
	}

	/**
	 * 修改位置图标
	 * 
	 * @param marker
	 */
	public void modifyLocationOverlayIcon(Drawable marker) {
		// 当传入marker为null时，使用默认图标绘制
		myLocationOverlay.setMarker(marker);
		// 修改图层，需要刷新MapView生效
		mMapView.refresh();
	}

	/**
	 * 创建弹出泡泡图层
	 */
	public void createPaopao() {
		viewCache = getLayoutInflater()
				.inflate(R.layout.custom_text_view, null);
		popupText = (TextView) viewCache.findViewById(R.id.textcache);
		// 泡泡点击响应回调
		PopupClickListener popListener = new PopupClickListener() {
			@Override
			public void onClickedPopup(int index) {
				Log.v("click", "clickapoapo");
			}
		};
		pop = new PopupOverlay(mMapView, popListener);
		MyLocationMapView.pop = pop;
	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;

			locData.latitude = location.getLatitude();
			locData.longitude = location.getLongitude();
			// 如果不显示定位精度圈，将accuracy赋值为0即可
			locData.accuracy = location.getRadius();
			locData.direction = location.getDerect();
			moveToLocation(locData);
			// 首次定位完成
			isFirstLoc = false;
		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
		}
	}

	// 继承MyLocationOverlay重写dispatchTap实现点击处理
	public class locationOverlay extends MyLocationOverlay {

		public locationOverlay(MapView mapView) {
			super(mapView);
			this.setMarker(getResources().getDrawable(R.drawable.ic_marker));
		}

		@Override
		protected boolean dispatchTap() {
			// 处理点击事件,弹出泡泡
			popupText.setBackgroundResource(android.R.drawable.menu_frame);
			popupText.setText("我的位置");
			pop.showPopup(BMapUtil.getBitmapFromView(popupText), new GeoPoint(
					(int) (locData.latitude * 1e6),
					(int) (locData.longitude * 1e6)), 8);
			return true;
		}

	}

	@Override
	protected void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onStart() {
		LocationData locData = new LocationData();
		// 手动将位置源置为天安门，在实际应用中，请使用百度定位SDK获取位置信息，要在SDK中显示一个位置，需要使用百度经纬度坐标（bd09ll）
		// locData.latitude = 39.945;
		// locData.longitude = 116.404;
		// locData.direction = 2.0f;
		locData.latitude =39.945;
		locData.longitude = 116.404;
		locData.direction = 2.0f;
		// 114.412736,30.460622
		moveToLocation(locData);
		// identifier
		// CMD命令值 user_showpoint
		// 参数列表 identifier 10753
		// 结果示例 成功 {"uid":"152690301","coordinate":"2631469,9884232"}
		// 失败 {"uid":"152690301","coordinate":"2631469,9884232"}
		super.onStart();
	}

	@Override
	protected void onDestroy() {
		// 退出时销毁定位
		if (mLocClient != null)
			mLocClient.stop();
		mMapView.destroy();
		super.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mMapView.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	private void moveToLocation(LocationData locData) {
		// 更新定位数据
		myLocationOverlay.setData(locData);
		lg.i(TAG, "moveToLocation->Lat:" + locData.latitude + "Lon:"
				+ locData.longitude + ":" + locData.direction);
		// 更新图层数据执行刷新后生效
		mMapView.refresh();
		// 是手动触发请求或首次定位时，移动到定位点
		if (isRequest || isFirstLoc && mMapController != null) {
			// 移动地图到定位点
			Log.d("LocationOverlay", "receive location, animate to it");
			mMapController.animateTo(new GeoPoint(
					(int) (locData.latitude * 1e6),
					(int) (locData.longitude * 1e6)));
			isRequest = false;
			myLocationOverlay.setLocationMode(LocationMode.FOLLOWING);
			requestLocButton.setText("跟随");
			mCurBtnType = E_BUTTON_TYPE.FOLLOW;
		}
	}

	@Override
	public void onBackPressed() {
		GlobalVariable.getGlobalInstance().intent.putExtra(
				IntentExtraDataKey.KEY_GOMAP_FOR,
				IntentExtraDataKey.KEY_UNVALUE_UNKNOW);
		super.onBackPressed();
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.sendMessage:
			if (editText1.getText() != null && editText1.getText().length() > 0) {
				sendMessageToHandleHit(editText1.getText().toString());
			} else {
				editText1.requestFocus();
				editText1.setError(getString(R.string.error_field_required));
			}
			break;
		case R.id.pickImage:
			Intent intent = new Intent();
			intent.setClass(this, ImageUploadActivity.class);
			if (view.getTag() != null) {
				intent.putExtra(ImageUploadActivity.LocalImageUrl, view
						.getTag().toString());
			}
			startActivityForResult(intent,
					ImageUploadActivity.RequestCode_ImageUpload);
			break;
		default:
			break;
		}
	}

	/**
	 * 处理碰撞
	 * 
	 * @param string
	 *            碰撞处理的描述性文字
	 */
	private void sendMessageToHandleHit(String string) {
		// TODO 处理碰撞 hit_remark
		AjaxParams par = new AjaxParams();
		if (json_hitInfo == null) {
			Tip.show("碰撞信息为空.");
			return;
		}
		int hitId = json_hitInfo.optInt("hitId");
		if (TextUtils.isEmpty(string)) {
			Tip.show(R.string.not_null);
			return;
		}
		par.put("hitId", String.valueOf(hitId));
		par.put("remark", string);
		ds.getData("hit_remark", null, par, new AjaxCallBackProxy<String>(
				findViewById(R.id.loading)) {
			@Override
			public void onSuccess(String t) {
				lg.i(TAG, t);
				int code = 0;
				String mesage = "";
				try {
					JSONObject result = new JSONObject(t);
					code = result.optInt(webkey.code);
					mesage = result.optString(webkey.reason);
				} catch (JSONException e) {
					e.printStackTrace();
					mesage = e.getMessage();
				} finally {
					if (code != 0) {
						loadFailed(mesage);
					} else {
						loadSuccessed();
						Tip.show("处理成功");
						setResult(RESULT_OK);
						onBackPressed();
					}
				}

			}
		});

	}

	public void receiveImageUploadResult(String message, Intent intent) {
		if (TextUtils.isEmpty(message)) {
			return;
		}
		JSONArray temp;
		try {
			temp = new JSONArray(message);
			imageUrl = temp.optJSONObject(0).optString("productImage");
			ImageView pickImage = (ImageView) findViewById(R.id.pickImage);
			String localImageUrl = intent
					.getStringExtra(ImageUploadActivity.LocalImageUrl);
			ImageLoader.getInstance().displayImage("file://" + localImageUrl,
					pickImage);
			pickImage.setTag(intent
					.getStringExtra(ImageUploadActivity.LocalImageUrl));
			pickImage.startAnimation(AnimationUtils.loadAnimation(this,
					R.anim.fade_in_two_second));
			lg.i(TAG, "receiveImageUploadResult:" + imageUrl);
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			if (data != null) {
				receiveImageUploadResult(
						data.getStringExtra(ImageUploadActivity.ImageUploadResuleExtraKey),
						data);
			}
		}
	}
}

/**
 * 继承MapView重写onTouchEvent实现泡泡处理操作
 * 
 * @author hejin
 * 
 */
class MyLocationMapView extends MapView {
	static PopupOverlay pop = null;// 弹出泡泡图层，点击图标使用

	public MyLocationMapView(Context context) {
		super(context);
	}

	public MyLocationMapView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public MyLocationMapView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (!super.onTouchEvent(event)) {
			// 消隐泡泡
			if (pop != null && event.getAction() == MotionEvent.ACTION_UP)
				pop.hidePop();
		}
		return true;
	}

}
